const webSocket=require("ws")

let onlineUser={}

let myWs=new webSocket.Server({port:9999})

myWs.on("connection",(userClient)=>{
    userClient.on("message",(msg)=>{
        let msgObj=JSON.parse(msg)
        if(msgObj.self){
            let userID=msgObj.self
            // console.log(msgObj.self)
            // let userID=msgObj.self
            // onlineUser[userID]=userClient
            // userClient.userID=userID
            userClient.userID=userID
            onlineUser[userID]=userClient
        }else {
            sendClient(msg,userClient)
        }
    })
    userClient.on("close",()=>{
        console.log("用户离线")
        // delete onlineUser[userClient.userID]
        // console.log(onlineUser)
    })
    userClient.send("您以上线")
})


function sendClient(msg,client){
    msg=JSON.parse(msg)
    for(let i in onlineUser){
        console.log(i+":"+client.userID)
        if(i!=client.userID){
            console.log(123)
            onlineUser[i].send(JSON.stringify({"sendID":client.userID,"value":msg.value}))
        }
    }
}